package com.studentbook.servlet;

import com.studentbook.bean.StudentContact;
import com.studentbook.service.StudentContactService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 更新联系人Servlet
 */
@WebServlet("/updateContact")
public class UpdateContactServlet extends HttpServlet {
    private StudentContactService contactService = new StudentContactService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取请求参数
        String studentId = request.getParameter("studentId");
        
        if (studentId != null && !studentId.trim().isEmpty()) {
            // 根据学号查询联系人
            StudentContact contact = contactService.getContactByStudentId(studentId);
            
            if (contact != null) {
                // 将联系人信息放入请求属性
                request.setAttribute("contact", contact);
                // 转发到编辑页面
                request.getRequestDispatcher("/edit.jsp").forward(request, response);
                return;
            }
        }
        
        // 如果没有找到联系人，重定向到联系人列表页面
        response.sendRedirect(request.getContextPath() + "/listContacts");
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取请求参数
        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String grade = request.getParameter("grade");
        String contactInfo = request.getParameter("contactInfo");
        
        // 参数校验
        if (studentId == null || studentId.trim().isEmpty() ||
            name == null || name.trim().isEmpty()) {
            request.setAttribute("message", "学号和姓名不能为空！");
            request.getRequestDispatcher("/edit.jsp").forward(request, response);
            return;
        }
        
        // 创建联系人对象
        StudentContact contact = new StudentContact(studentId, name, grade, contactInfo);
        
        // 更新联系人
        boolean success = contactService.updateContact(contact);
        
        if (success) {
            // 更新成功，重定向到联系人列表页面
            response.sendRedirect(request.getContextPath() + "/listContacts");
        } else {
            // 更新失败，返回编辑页面并显示错误信息
            request.setAttribute("message", "更新失败，学号可能不存在！");
            request.setAttribute("contact", contact);
            request.getRequestDispatcher("/edit.jsp").forward(request, response);
        }
    }
}